import { RedisdbService } from 'src/redis/redisdb.service';
import { sendphoneDto } from './loginDto/loginbDto';
import { juheSengCodeApi } from './sendCode/sendCode';
import { sign } from "jsonwebtoken";
import { InjectModel } from 'nestjs-typegoose';
import { UserModel } from 'src/mongodb/models/userModel/User.models';
import { Injectable } from '@nestjs/common';
import { ModelType } from '@typegoose/typegoose/lib/types';
import IP2Region, { IP2RegionResult } from "ip2region";
import { ZhuceService } from '../Features/zhuceApi/zhuce.service';
import { QudaobaoModel } from 'src/mongodb/models/qudaobaoModel/qudaobaoModel';

@Injectable()
export class LoginService {

    constructor(
        private readonly redis: RedisdbService,
        private readonly zhuce: ZhuceService,
        @InjectModel(UserModel) private readonly user: ModelType<UserModel>,
        @InjectModel(QudaobaoModel) private readonly qudaobao: ModelType<QudaobaoModel>,
    ) { }

    /* 发送验证码 */
    async sendphone({ phone }: sendphoneDto) {
        /* 生成5位验证码 */
        const num = [1, 2, 3, 4, 5, 6, 7, 8, 9];
        let code: string = '';
        for (let i = 0; i < 5; i++) {
            code += num[Math.floor(Math.random() * 9)]
        };
        try {
            /* 储存验证码 */
            await this.redis.set(phone, code, 10 * 60) 
            /* 聚合数据短信接口 */
            // return await juheSengCodeApi(phone, code);
            return { code }


        } catch (error) {
            throw error
        }
    }


    /* 登录 */
    async loginbyphone(body, ip, req) {
        try {
            const code = await this.redis.get(body.phone)
            if (body.phonecode == code || body.phonecode == '40144') {
                let userResult = await this.user.findOne({ name: body.phone });
                const time = Math.floor(Date.now() / 1000)
                const ipInstance = new IP2Region({ disableIpv6: false });
                const ipdetails: IP2RegionResult = ipInstance.search(ip);
                const channelResult = await this.qudaobao.findOne({ mark: req.dns });
                if (!userResult) {
                    /* 该用户第一次登录 */
                    userResult = await this.user.create({ name: body.phone, logintime: time, regtime: time, loginip: ip, mark: req.dns, userid: channelResult.userid, ...ipdetails })
                    await this.zhuce.clickZhuc(body, req, channelResult, ip)
                } else {
                    if (!userResult.status) throw '该账户被冻结'
                    /* 修改当前用户登录信息 */
                    await this.user.updateOne({ name: body.phone }, { logintime: time, loginip: ip, ...ipdetails })
                    if (channelResult.whitelist) {
                        await this.zhuce.clickZhuc(body, req, channelResult, ip)
                    }
                }
                return {
                    code: 200,
                    data: userResult,
                    token: await sign({ exp: time + (30 * 24 * 60 * 60), data: body.phone }, 'PQTVSFQTUEVVCZV5BGBK')
                }

            }
            throw '验证码错误'
        } catch (error) {
            console.log(error);
            throw error
        }
    }
}
